package com.android.guoqi.sms

import android.annotation.TargetApi
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.PowerManager
import android.provider.Settings
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.KeyEvent
import com.android.guoqi.sms.App.Companion.smsReceiver
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject


class MainActivity : AppCompatActivity() {

    private var checker: PermissionsUtil? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        checker = PermissionsUtil(this)
        checker!!.checkPermissions(PermissionsUtil.PERMISSIONS)
        setContentView(R.layout.activity_main)
        startService(Intent(this, SmsService::class.java))
        initView()
    }


    private fun initView() {
        smsReceiver?.setOnReceivedMessageListener(object : SmsReceiver.MessageListener {
            override fun OnReceived(sender: String, content: String, time: String) {
                tv_tel.text = sender
                tv_body.text = content
                tv_time.text = time
                if (content.contains("【百度】验证码")) {
                    tv_verity_code.text = content.substring(8, 14)
                } else {
                    tv_verity_code.text = ""
                }


                if (content.contains("【百度】验证码")) {
                    val params = JSONObject()
                    params.put("sender", sender)
                    params.put("content", content)
                    params.put("time", time)
                    params.put("code", content.substring(8, 14))
                    OkGo.post<String>("http://oaapi.yingfeng365.com/jsyf-oa/vertify/save.json")
                            .upJson(params.toString())
                            .execute(object : StringCallback() {
                                override fun onSuccess(response: Response<String>) {
                                    Log.e("SmsService", response?.body().toString())
                                }
                            })
                }
            }

        })
    }

    override fun onResume() {
        super.onResume()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val powerManager = getSystemService(POWER_SERVICE) as PowerManager
            var isIgnoring = powerManager.isIgnoringBatteryOptimizations(packageName)
            if (!isIgnoring) {
                var intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                intent.data = Uri.parse("package:$packageName")
                try {
                    startActivity(intent)
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }
            }
        }
    }

    /**
     * 在该声明周期,检查权限申请情况
     */
    override fun onStart() {
        super.onStart()
        checker!!.checkPermissions(PermissionsUtil.PERMISSIONS)
    }

    /**
     * 请求权限检查完后回调的结果
     *
     * @param requestCode
     * @param permissions  所请求的权限
     * @param grantResults
     */
    @TargetApi(Build.VERSION_CODES.M)
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || requestCode != PermissionsUtil.PERMISSION_REQUEST_CODE) {
            return
        }
        var i = 0
        val len = permissions.size
        while (i < len) {
            val permission = permissions[i]
            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                val showRationale = shouldShowRequestPermissionRationale(permission)
                if (!showRationale) {
                    // 用户点击不再提醒,弹出权限框,引导其手动开启权限
                    checker!!.showMissingPermissionDialog()
                    break
                } else {
                    // 用户点击取消,继续提示
                    checker!!.checkPermissions(PermissionsUtil.PERMISSIONS)
                    break
                }
            }
            i++
        }
    }

    //按返回键程序仍在后台运行
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

}
